package com.mlizhi.modules.spec.content;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mlizhi.base.MlzApplication;
import com.mlizhi.base.Session;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.ISpecInterface;
import com.mlizhi.modules.spec.dao.DaoSession;
import com.mlizhi.utils.Constants;
import com.mlizhi.widgets.waterfall.internal.PLA_AbsListView.LayoutParams;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SpecContentFragment extends Fragment implements OnPageChangeListener {
    // 缓存Fragment view
    private View rootView;
    // ISpecInterface的实例，用来使SpecActivity做回调的
    private ISpecInterface specCallback;

    private Activity mContext;


    private static SpecContentFragment specContentFragment;
    private Session mSession;
    private DaoSession daoSession;
    private MlzApplication mlzApplication;
    private LinearLayout advertiseLayout = null;
    private View contentProduct01, contentProduct02, contentProduct03, contentProduct04, contentProduct05, contentProduct06, contentProduct07, contentProduct08,
            contentProduct09, contentProduct10, contentProduct11, contentProduct12, contentProduct13, contentProduct14, contentProduct15, contentProduct16, contentProduct17,
            contentProduct18, contentProduct19, contentProduct20;

    private LayoutInflater mInflater;

    public SpecContentFragment() {

    }

    public static SpecContentFragment getNewInstance() {
        if (specContentFragment == null) {
            specContentFragment = new SpecContentFragment();
        }
        return specContentFragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mlzApplication = (MlzApplication) getActivity().getApplication();
        mSession = Session.get(getActivity().getApplicationContext());
        daoSession = mlzApplication.getDaoSession();
        this.mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_spec_content, container, false);
            advertiseLayout = (LinearLayout) rootView.findViewById(R.id.id_content_advertise);
            contentProduct01 = rootView.findViewById(R.id.id_content_product_01);
            contentProduct02 = rootView.findViewById(R.id.id_content_product_02);
            contentProduct03 = rootView.findViewById(R.id.id_content_product_03);
            contentProduct04 = rootView.findViewById(R.id.id_content_product_04);
            contentProduct05 = rootView.findViewById(R.id.id_content_product_05);
            contentProduct06 = rootView.findViewById(R.id.id_content_product_06);
            contentProduct07 = rootView.findViewById(R.id.id_content_product_07);
            contentProduct08 = rootView.findViewById(R.id.id_content_product_08);
            contentProduct09 = rootView.findViewById(R.id.id_content_product_09);
            contentProduct10 = rootView.findViewById(R.id.id_content_product_10);
            contentProduct11 = rootView.findViewById(R.id.id_content_product_11);
            contentProduct12 = rootView.findViewById(R.id.id_content_product_12);
            contentProduct13 = rootView.findViewById(R.id.id_content_product_13);
            contentProduct14 = rootView.findViewById(R.id.id_content_product_14);
            contentProduct15 = rootView.findViewById(R.id.id_content_product_15);
            contentProduct16 = rootView.findViewById(R.id.id_content_product_16);
            contentProduct17 = rootView.findViewById(R.id.id_content_product_17);
            contentProduct18 = rootView.findViewById(R.id.id_content_product_18);
            contentProduct19 = rootView.findViewById(R.id.id_content_product_19);
            contentProduct20 = rootView.findViewById(R.id.id_content_product_20);

            //************************************
            mInflater = LayoutInflater.from(getActivity());
            //add header view.
            View headerView = mInflater.inflate(R.layout.content_view_header, null);
            // 初始化imageviews集合
            for (int i = 0; i < drawables.length; i++) {
                imageViews.add(new ImageView(getActivity()));

            }

            // 初始化布局文件中的view
            advertisePoints = (LinearLayout) headerView.findViewById(R.id.advertise_points);
            advertiseDes = (TextView) headerView.findViewById(R.id.advertise_slogan);
            advertiseDes.setText(descriptions[0]);
            viewPager = (ViewPager) headerView.findViewById(R.id.advertise_view_pager);

            // 初始化小点
            initPointGroup();

            advertiseAdapter = new AdvertiseAdapter();
            viewPager.setAdapter(advertiseAdapter);

            // 设置初始的时候在Integer一半附近的第一张图的位置上
            viewPager.setCurrentItem(0);
            viewPager.setOnPageChangeListener(this);
            advertiseLayout.addView(headerView);

        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        specCallback = (ISpecInterface) getActivity();
        contentProduct01.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                String url = "https://detail.m.tmall.com/item.htm?id=44426993148";
//                Uri uri = Uri.parse(url); // 商品地址
//                intent.setData(uri);
//                intent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
//                startActivity(intent);
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=528355629604";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct02.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=44426993148";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct03.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                String url = "http://ok.jd.com/m/index-150602.htm";
//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                Uri content_url = Uri.parse(url);
//                intent.setData(content_url);
//                startActivity(intent);
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=531550480465";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct04.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=528355629604";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct05.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=44426993148";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct06.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=529080916195";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct07.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=18813465838";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct08.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=36407485288";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct09.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=39609820178";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct10.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=525500625029";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct11.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=530139142720";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct12.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=520129490169";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct13.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=44689834486";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct14.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=531550480465";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct15.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=527994185660";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct16.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=531550480465";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct17.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "http://www.kingdomcares.com/";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct18.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=19036862765";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct19.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "http://www.kingdomcares.com/";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });
        contentProduct20.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                String url = "https://detail.m.tmall.com/item.htm?id=18740889154";
                intent.putExtra(Constants.CONTENT_ITEM_URL,url);
                startActivity(intent);
            }
        });

        //************************************
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        startPlay();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    //**********************************************
    private ViewPager viewPager;
    //广告图片的路径
    private int[] drawables = {R.drawable.ic_advertise_01, R.drawable.ic_advertise_02, R.drawable.ic_advertise_03, R.drawable.ic_advertise_04};// 图片描述
    private String[] descriptions = {"", "", "", ""};

    // 装点点的ImageView数组
    private List<ImageView> imageViews = new ArrayList<ImageView>();

    private AdvertiseAdapter advertiseAdapter;


    private LinearLayout advertisePoints;
    private TextView advertiseDes;

    private ImageView[] tips;


    private void initPointGroup() {

        // 将点点加入到ViewGroup中
        tips = new ImageView[drawables.length];
        for (int i = 0; i < tips.length; i++) {

            ImageView imageView = new ImageView(getActivity());
            tips[i] = imageView;
            if (i == 0) {
                tips[i].setBackgroundResource(R.drawable.ic_splash_indicator_focused);
            } else {
                tips[i].setBackgroundResource(R.drawable.ic_splash_indicator);
            }

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
            layoutParams.leftMargin = 5;
            layoutParams.rightMargin = 5;
            advertisePoints.setGravity(Gravity.CENTER_VERTICAL);
            advertisePoints.addView(imageView, layoutParams);
        }
    }

    /**
     * 设置选中的tip的背景
     *
     * @param selectItems
     */
    private void setImageBackground(int selectItems) {
        for (int i = 0; i < tips.length; i++) {
            if (i == selectItems) {
                tips[i].setBackgroundResource(R.drawable.ic_splash_indicator_focused);
            } else {
                tips[i].setBackgroundResource(R.drawable.ic_splash_indicator);
            }
        }
    }


    private class AdvertiseAdapter extends PagerAdapter {

        List<ImageView> tempImageViews = imageViews;
        int[] tempDrawables = drawables;
        String[] tempDesc = descriptions;
        TextView tempDescTextView = advertiseDes;

        @Override
        public int getCount() {
            // return ids.length;
            return imageViews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            // TODO Auto-generated method stub
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = tempImageViews.get(position);
            try {
                imageView.setImageResource(tempDrawables[position]);
                imageView.setScaleType(ScaleType.CENTER_CROP);
                // 把id与imageview通过setTag方法挂钩起来
                imageView.setTag(tempDrawables[position]);
//					setImageBackground(position);
                tempDescTextView.setText(tempDesc[position]);

                imageView.setClickable(true);
                imageView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(mContext,SpecContentViewActivity.class);
                        String url = "";
                        if(position == 0){
                            url = "http://tv.le.com/izt/fanyiguan/index.html";
                        }else if(position == 1){
                            url = "http://jindaogrhl.m.tmall.com/";
                        }else if(position == 2){
                            url = "http://ok.jd.com/m/index-150602.htm";
                        }else if(position == 3) {
                            url = "https://detail.m.tmall.com/item.htm?id=44426993148";
                        }
                        intent.putExtra(Constants.CONTENT_ITEM_URL, url);
                        startActivity(intent);
                    }
                });
                ((ViewPager) container).addView(imageView);
            } catch (Exception e) {

            }
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            object = null;
//			    ((ViewPager)container).removeView(tempImageViews.get(position % drawables.length));  
        }
    }
    //*********************************************


    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub
        System.out.println(arg0);
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub
        System.out.println(arg0);
    }

    @Override
    public void onPageSelected(int position) {
        viewPager.setCurrentItem(position);
        setImageBackground(position);
    }

    int currentItem = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            viewPager.setCurrentItem(currentItem);
        }
    };

    /**
     * 执行轮播图切换任务
     *
     * @author caizhiming
     */
    private class SlideShowTask implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (viewPager) {
                currentItem = (currentItem + 1) % 3;
                handler.obtainMessage().sendToTarget();
            }
        }
    }

    //定时任务
    private ScheduledExecutorService scheduledExecutorService;

    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
    }

    /**
     * 停止轮播图切换
     */
    private void stopPlay() {
        scheduledExecutorService.shutdown();
    }

}
